﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace GamovMvc
{
    public class Global : System.Web.HttpApplication
    {
        private static IList<string> Routes;

        protected void Application_Start(object sender, EventArgs e)
        {
            // 路由规则
            Routes = new List<string>();
            Routes.Add("{controller}/{action}");
            Routes.Add("{controller}");
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            IDictionary<string, string> routeData = new Dictionary<string, string>();
            var executePath = Request.AppRelativeCurrentExecutionFilePath;
            if (string.IsNullOrEmpty(executePath) || executePath.Equals("~/"))
            {
                executePath += "/home/index";
            }

            foreach (var item in Routes)
            {
                var pathArr = executePath.Substring(2).Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                var routeArr = item.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (pathArr.Length != routeArr.Length)
                {
                    continue;
                }
                for (int i = 0; i < routeArr.Length; i++)
                {
                    routeData.Add(routeArr[i], pathArr[i]);
                }
                Context.RemapHandler(new MvcHandler(routeData));
                break;
            }

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}